package cn.harry.cabinet.model.ui

import cn.harry.cabinet.model.entity.HardwareDevice
import cn.harry.cabinet.model.enums.DeviceType
import java.util.Date

/**
 * 硬件设备配置数据类
 */
data class HardwareDeviceUI(
    val deviceType: DeviceType,
    val deviceName: String,
    val serialPort: String = "/dev/ttyS3",
    val baudRate: Int = 9600,
    val dataBits: Int = 8,
    val stopBits: Int = 1,
    val parity: ParityType = ParityType.NONE,
    val enabled: Boolean = true
) {

    enum class ParityType(val displayName: String, val value: Int) {
        NONE("无校验", 0),
        ODD("奇校验", 1),
        EVEN("偶校验", 2)
    }

    companion object {
        /**
         * 获取默认的刷卡器配置
         */
        fun getDefaultCardReaderConfig(): HardwareDeviceUI {
            return HardwareDeviceUI(
                deviceType = DeviceType.CARD_READER,
                deviceName = "刷卡器",
                serialPort = "/dev/ttyS4",
                baudRate = 9600,
                dataBits = 8,
                stopBits = 1,
                parity = ParityType.NONE,
                enabled = true
            )
        }

        /**
         * 从数据库实体创建设备配置
         */
        fun fromEntity(entity: HardwareDevice): HardwareDeviceUI {
            return HardwareDeviceUI(
                deviceType = entity.deviceType,
                deviceName = entity.deviceName,
                serialPort = entity.serialPort,
                baudRate = entity.baudRate,
                dataBits = entity.dataBits,
                stopBits = entity.stopBits,
                parity = when (entity.parity) {
                    0 -> ParityType.NONE
                    1 -> ParityType.ODD
                    2 -> ParityType.EVEN
                    else -> ParityType.NONE
                },
                enabled = entity.enabled
            )
        }
    }

    /**
     * 转换为数据库实体
     */
    fun toEntity(): HardwareDevice {
        return HardwareDevice(
            deviceType = deviceType,
            deviceName = deviceName,
            serialPort = serialPort,
            baudRate = baudRate,
            dataBits = dataBits,
            stopBits = stopBits,
            parity = parity.value,
            enabled = enabled,
            createTime = Date(),
            updateTime = Date()
        )
    }
}